package com.fuelchooser;

import java.text.NumberFormat;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class FuelChooserActivity extends Activity {
    
	private EditText gasolinePriceField;
	private EditText etanolPriceField;
	private TextView chooseText;
	private ImageView fuelImg;
	
	NumberFormat nf;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextWatcher textWatcher = new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) { }
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
			
			public void afterTextChanged(Editable s) {
    			update();
			}
		};

        gasolinePriceField = (EditText) findViewById(R.id.gasolinePriceField);
		gasolinePriceField.addTextChangedListener(textWatcher);

        etanolPriceField = (EditText) findViewById(R.id.etanolPriceField);
		etanolPriceField.addTextChangedListener(textWatcher);
		
		chooseText = (TextView) findViewById(R.id.chooseText);
		
		fuelImg = (ImageView) findViewById(R.id.fuelImg);

		nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(4);
    }
    
    void update() {
    	try { 
    		String etanolPriceText = this.etanolPriceField.getText().toString();
    		String gasolinePriceText = this.gasolinePriceField.getText().toString();
    		if (etanolPriceText.length() == 0  || gasolinePriceText.length() == 0) {
    			this.chooseText.setText("");
    			this.fuelImg.setImageResource(R.drawable.bluefuel);
    		}
    		else {
    			double maxEtanolPrice = Double.parseDouble(gasolinePriceText)*0.7;					
    			double maxGasolinaPrice = Double.parseDouble(etanolPriceText)/0.7;					
    			if (Double.parseDouble(etanolPriceText) <= maxEtanolPrice) {
    				this.chooseText.setText("ETANOL (max. R$ " + 
    						nf.format(maxEtanolPrice) + ")");
    				this.fuelImg.setImageResource(R.drawable.greenfuel);
    			}
    			else {
    				this.chooseText.setText("GASOLINA (max. R$ " + 
    						nf.format(maxGasolinaPrice) + ")");
    				this.fuelImg.setImageResource(R.drawable.redfuel);
    			}
    		}
    	} catch (NumberFormatException e) {
    		this.chooseText.setText("ERRO!!!");
    		this.fuelImg.setImageResource(R.drawable.bluefuel);
    	}
    }
    
}

